package com.guyaogg.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guyaogg.common.to.mq.OrderTo;
import com.guyaogg.common.to.mq.StockDetailTo;
import com.guyaogg.common.to.mq.StockLockedTo;
import com.guyaogg.common.utils.PageUtils;
import com.guyaogg.common.utils.Query;
import com.guyaogg.common.utils.R;
import com.guyaogg.common.utils.StringUtils;
import com.guyaogg.gulimall.ware.dao.WareSkuDao;
import com.guyaogg.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.guyaogg.gulimall.ware.entity.WareOrderTaskEntity;
import com.guyaogg.gulimall.ware.entity.WareSkuEntity;
import com.guyaogg.gulimall.ware.exception.NoStockException;
import com.guyaogg.gulimall.ware.feign.OrderFeignService;
import com.guyaogg.gulimall.ware.feign.ProductFeignService;
import com.guyaogg.gulimall.ware.service.WareOrderTaskDetailService;
import com.guyaogg.gulimall.ware.service.WareOrderTaskService;
import com.guyaogg.gulimall.ware.service.WareSkuService;
import com.guyaogg.gulimall.ware.vo.OrderItemVO;
import com.guyaogg.gulimall.ware.vo.SkuHasStockVO;
import com.guyaogg.gulimall.ware.vo.WareSkuLockVO;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    private WareSkuDao wareSkuDao;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private WareOrderTaskDetailService wareOrderTaskDetailService;
    @Autowired
    private WareOrderTaskService wareOrderTaskService;
    @Autowired
    private OrderFeignService orderFeignService;


    private void unLockStock(Long skuId, Long wareId, Integer count, Long taskDetailId) {
        // 库存解锁
        wareSkuDao.unLockStock(skuId, wareId, count);
        // 跟新库存工作单状态
        WareOrderTaskDetailEntity entity = new WareOrderTaskDetailEntity();
        entity.setId(taskDetailId);
        entity.setLockStatus(2);
        wareOrderTaskDetailService.updateById(entity);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        /*
        {
            page: 1,//当前页码
            limit: 10,//每页记录数
            sidx: 'id',//排序字段
            order: 'asc/desc',//排序方式
            wareId: 123,//仓库id
            skuId: 123//商品id
            }
         */
        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId)) {
            wrapper.eq("sku_id", skuId);
        }
        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId)) {
            wrapper.eq("ware_id", wareId);
        }
        IPage<WareSkuEntity> page = this.page(

                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }


    @SuppressWarnings("AlibabaTransactionMustHaveRollback")
    @Transactional
    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        List<WareSkuEntity> wareSkuEntities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if (wareSkuEntities.isEmpty()) {
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setStockLocked(0);
            // TODO 远程查询 skuName 如果失败，整个事件无需回滚
            // 远程查询 skuName
            // TODO 远程查询 skuName 如果失败，另一种无需回滚方法，高级篇
            try {
                R info = productFeignService.info(skuId);
                if (info.getCode() == 0) {
                    Map<String, Object> skuInfo = (Map<String, Object>) info.get("skuInfo");
                    wareSkuEntity.setSkuName((String) skuInfo.get("skuName"));

                }
            } catch (Exception ignored) {

            }
            wareSkuDao.insert(wareSkuEntity);
        } else {
            wareSkuDao.addStock(skuId, wareId, skuNum);

        }
    }

    @Override
    public List<SkuHasStockVO> getSkusHasStock(List<Long> skuIds) {
        return skuIds.stream().map(skuId -> {
            SkuHasStockVO skuHasStockVO = new SkuHasStockVO();
            Long count = this.baseMapper.getSkuHasStock(skuId);
            skuHasStockVO.setSkuId(skuId);
            skuHasStockVO.setHasStock(count != null && count > 0);
            return skuHasStockVO;
        }).collect(Collectors.toList());
    }

    /**
     * 为某个订单锁定库存
     *
     * @param vo 订单对象
     *           库存解锁场景
     *           1）下订单成功，订单过期没有支付自动解锁；被用户手动取消。都要解锁库存
     *           2）下订单成功，库存锁定成功，接下来的业务调用失败。导致订单回滚。
     *           之后自动解锁
     * @return
     */
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public Boolean orderLockStock(WareSkuLockVO vo) {

        /*
        引入库存工作单的详情
        追溯
         */
        // 先保存工作单
        WareOrderTaskEntity wareOrderTaskEntity = new WareOrderTaskEntity();
        wareOrderTaskEntity.setOrderSn(vo.getOrderSn());
        wareOrderTaskService.save(wareOrderTaskEntity);
        // TODO 以后实现1.按照下单的收货地址，找到就近仓库，锁定库存
        // 1.找到每个商品在哪个仓库有库存
        List<OrderItemVO> locks = vo.getLocks();
        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            SkuWareHasStock stock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            stock.setSkuId(skuId);
            stock.setCount(item.getCount());
            // 查询商品在哪里有库存
            List<Long> wareIds = wareSkuDao.listWareIdHasSkuStock(skuId);
            stock.setWareId(wareIds);

            return stock;
        }).collect(Collectors.toList());

        // 2.锁定库存
        for (SkuWareHasStock hasStock : collect) {
            boolean skuStocked = false;
            Long skuId = hasStock.getSkuId();
            List<Long> wareIds = hasStock.getWareId();
            if (wareIds == null || wareIds.size() == 0) {
                // 没有任何仓库有这个商品的库存
                throw new NoStockException(skuId);
            }
            // 1.如果锁成功，将当前锁定工作单发给 MQ
            // 2.如果锁定失败。前面的保持的工作单信息回滚了。发送出去的消息即使要解锁记录，也没事，因为没有
            //       不合理
            for (Long wareId : wareIds) {
                // 成功返回 1，否则就是 0
                Long count = wareSkuDao.lockSkuStock(skuId, wareId, hasStock.getCount());
                if (count > 0) {
                    // 锁定成功
                    skuStocked = true;
                    // TODO 告诉 mq 库存锁定成功
                    // 锁成功详情
                    WareOrderTaskDetailEntity wareOrderTaskDetailEntity = new WareOrderTaskDetailEntity();
                    wareOrderTaskDetailEntity.setSkuId(skuId);
                    wareOrderTaskDetailEntity.setSkuNum(hasStock.getCount());
                    wareOrderTaskDetailEntity.setTaskId(wareOrderTaskEntity.getId());
                    wareOrderTaskDetailEntity.setWareId(wareId);
                    wareOrderTaskDetailEntity.setLockStatus(1);
                    wareOrderTaskDetailService.save(wareOrderTaskDetailEntity);

                    StockLockedTo stockLockedTo = new StockLockedTo();
                    stockLockedTo.setId(wareOrderTaskEntity.getId());
                    StockDetailTo stockDetailTo = new StockDetailTo();
                    BeanUtils.copyProperties(wareOrderTaskDetailEntity, stockDetailTo);
                    stockLockedTo.setDetail(stockDetailTo);
                    rabbitTemplate.convertAndSend("stock-event-exchange", "stock.locked", stockLockedTo);
                    break;
                }
                // 锁定失败，重试下一个

            }
            if (!skuStocked) {
                // 当前所有仓库都没有锁住
                throw new NoStockException(skuId);
            }
        }
        // 3.全部锁定成功
        return true;
    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public void unlockStock(StockLockedTo to) {
        log.debug("收到解锁库存的消息");
        // 库存工作单的 id
        Long id = to.getId();
        StockDetailTo detail = to.getDetail();
        Long skuId = detail.getSkuId();
        // 解锁
        // 1.查询数据库关于这个订单锁定库存信息。
        // 有：证明库存锁定成功了
        // 没有：库存锁定失败了，库存回滚了，无需解锁
        WareOrderTaskDetailEntity byId = wareOrderTaskDetailService.getById(detail.getId());
        if (byId != null) {
            // 解锁
            // 没有这个订单。必须解锁
            // 有这个订单。不是解锁库存
            // 订单状态，已取消，解锁库存
            // 其他状态，不解锁
            WareOrderTaskEntity taskEntity = wareOrderTaskService.getById(id);
            String orderSn = taskEntity.getOrderSn();
            R r = orderFeignService.getOrderStatus(orderSn);
            if (r.getCode() == 0) {
                // 返回成功
                Integer orderStatus = r.getData(new TypeReference<Integer>() {
                });
                if (orderStatus == null || orderStatus == 4) {
                    // 订单被取消，解锁库存
                    if (byId.getLockStatus() == 1) {
                        // 状态已锁定，且未解锁才可以解锁
                        unLockStock(skuId, detail.getWareId(), detail.getSkuNum(), detail.getId());
                        log.debug("自动解锁库存成功");
                    }

                }
            } else {
                // 远程服务失败
                throw new RuntimeException("远程服务失败");
            }
        }
    }

    /**
     * 防止订单服务卡顿，导致订单状态一直改不了，
     *
     * @param to
     */
    @SuppressWarnings("AlibabaTransactionMustHaveRollback")
    @Transactional
    @Override
    public void unlockStock(OrderTo to) {
        String orderSn = to.getOrderSn();
        // 查一下最新状态，防止重复解锁
//        R r = orderFeignService.getOrderStatus(orderSn);
        WareOrderTaskEntity orderTaskEntity = wareOrderTaskService.getOrderTaskByOrderSn(orderSn);
        Long id = orderTaskEntity.getId();
        // 按照工作单，找到所有，没有解锁的库存，进行解锁
        List<WareOrderTaskDetailEntity> detailEntities = wareOrderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>().eq("task_id", id).eq("lock_status", 1));
        for (WareOrderTaskDetailEntity detailEntity : detailEntities) {
            unLockStock(detailEntity.getSkuId(), detailEntity.getWareId(),detailEntity.getSkuNum(),detailEntity.getId());
        }
    }

    @Data
    static class SkuWareHasStock {
        private Long skuId;
        private Integer count;
        private List<Long> wareId;
    }

}